﻿using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;
using static Learun.Application.TwoDevelopment.ZZDT_EC.ec_enginedataBLL;

namespace Learun.Application.Web.AppApi
{
    /// <summary>
    /// 工程数据
    /// </summary>
    [RoutePrefix("api/EnginedataApi")]
    [HandlerApiLogin(FilterMode.Enforce)]
    [TokenAuthorize]
    public class EnginedataApiController : WebApiControllerBase
    {
        /// <summary>
        /// 更新工程数据属性默认值
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult UpdateEnginedataPropertyByDefaultValue()
        {
            try
            {
                new ec_enginedataBLL().UpdateEngineDataByDefaultValue();
                return Success("更新成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取位号的pixel对象（仅有位号）.
        /// 插件端的设计浏览处用到
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="EngineDataID">对象类型ID</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(TreeModelLite))]
        public IHttpActionResult GetTagPixelsById(string projectId, string EngineDataID)
        {
            try
            {
                List<TreeModelLite> res = new List<TreeModelLite>();
                var ec_enginedata_pixelBLL = new ec_enginedata_pixelBLL();
                var data = ec_enginedata_pixelBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"EngineDataID\":\"" + EngineDataID + "\"}");

                return Success(data);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }


        /// <summary>
        /// 获取某个图上的所有pixel对象
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="drawingFileID"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetTagPixelsByDrawing(string projectId, string drawingFileID)
        {
            try
            {
                //var engineData = new ec_enginedataBLL().GetList("{\"ProjectId\":\"" + projectId + "\",\"DrawingFileID\":\"" + drawingFileID + "\",\"PixelCodes\":\"" + pixels + "\"}").ToList();
                var res = new ec_enginedata_pixelBLL().GetDrawingEnginePixel("{\"ProjectId\":\"" + projectId + "\",\"DrawingFileID\":\"" + drawingFileID + "\"}").ToList();

                return Success(res);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }


        /// <summary>
        /// 获取某个图上的所有位号(前端再根据情况进行过滤)
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="drawingFileID"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetTagsByDrawing(string projectId, string drawingFileID)
        {
            try
            {
                //var engineData = new ec_enginedataBLL().GetList("{\"ProjectId\":\"" + projectId + "\",\"DrawingFileID\":\"" + drawingFileID + "\",\"PixelCodes\":\"" + pixels + "\"}").ToList();
                var res = new ec_enginedataBLL().GetListByDrawing(projectId, drawingFileID);

                return Success(res);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }


        /// <summary>
        /// 批量反向关联
        /// </summary>
        /// <param name="projId"></param>
        /// <param name="entity">ID是设备的，而不是开关的</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult QuickAssign(string projId, [FromBody] IEnumerable<ec_enginedata_pixelEntity> entity)
        {

            #region 根据传过来的图元集合
            if (entity == null)
            {
                return Success("OK");
            }
            var ProjectEntity = SqlSugarHelper.Db.Queryable<ec_projectEntity>().Single(x => x.ProjectId == projId);
            foreach (var pixel in entity)
            {
                var existPixel = SqlSugarHelper.Db.Queryable<ec_enginedata_pixelEntity>().AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").
                    First(x => x.DrawingFileID == pixel.DrawingFileID && x.PixelCode == pixel.PixelCode);
                if (existPixel != null)
                {
                    existPixel.Modify(existPixel.EngineDataPixelID);
                    existPixel.DeleteFlg = 0;
                    existPixel.EngineDataID = pixel.EngineDataID;
                    existPixel.LibraryFileID = pixel.LibraryFileID;
                    existPixel.MaxPointX = pixel.MaxPointX;
                    existPixel.MinPointX = pixel.MinPointX;
                    existPixel.MaxPointY = pixel.MaxPointY;
                    existPixel.MinPointY = pixel.MinPointY;
                    SqlSugarHelper.Db.Updateable(existPixel).AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                }
                else
                {
                    pixel.Create();
                    pixel.DeleteFlg = 0;
                    pixel.EngineDataID = pixel.EngineDataID;
                    SqlSugarHelper.Db.Insertable(pixel).AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                }
                //SqlSugarHelper.Db.Ado.ExecuteCommand($" DELETE FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} WHERE DrawingFileID = '{pixel.DrawingFileID}' AND PixelCode = '{pixel.PixelCode}';");

            }
            return Success("OK");
            //db.InsertByNoMap(entity.EngineDataPixel, $"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}");

            #endregion
        }


        /// <summary>
        /// 成品导出（xlsx）,用于二三维联动用的，三维坐标信息。
        /// </summary>
        /// <param name="projectId">项目编号</param> 
        /// <param name="exportType"></param>
        /// <returns></returns>
        [HttpGet]
        public void ExportExcel(string projectId, ExportType exportType)
        {

            var BLL = new ec_enginedataBLL();
            var bytes = BLL.ExportExcel(projectId, exportType);


            var stream = new MemoryStream(bytes);
            FileDownHelper.DownLoad(stream, $"BricsCAD中坐标信息 {DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");
        }

    }
}
